//
//  Programs.m
//  iPLayer-ipad
//
//  Created by Chris Greening on 06/05/2010.
//  Copyright 2010 CMG Research. All rights reserved.
//

#import "Programs.h"
#import "TouchXML.h"
#import "ProgramInfo.h"
#import "ImageDownloaderQueue.h"

@interface Programs()

-(void) refresh;

@end


@implementation Programs

@synthesize tableView;
@synthesize feedUrl;
@synthesize delegate;
@synthesize tvRadioSwitch;

#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
    [super viewDidLoad];

	self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refresh)] autorelease];

	feedDownloader=[[HttpDownloader alloc] init];
	
	imageDownloader=[[ImageDownloaderQueue alloc] init];
	
	self.contentSizeForViewInPopover=CGSizeMake(600, 1100);
	
	[self refresh];
}
											  
-(void) refresh {
	[tvShows release];
	[radioShows release];
	tvShows=[[NSMutableArray alloc] init];
	radioShows=[[NSMutableArray alloc] init];
	[feedDownloader downloadDataFromUrl:feedUrl delegate:self];
}
											  
-(void) downloader:(HttpDownloader *) downloader downloadedData:(NSData *) data {
//	NSString *stringData=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//	NSLog(stringData);
	
	NSDateFormatter *dateParser = [[[NSDateFormatter alloc] init] autorelease];
	[dateParser setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
	
	CXMLDocument *xmlDoc=[[[CXMLDocument alloc] initWithData:data options:0 error:nil] autorelease];
	if(xmlDoc) {
		CXMLElement *root=xmlDoc.rootElement;
		if(root) {
			NSArray *entryNodes=[root elementsForName:@"entry"];
			if(entryNodes) {
				for(CXMLElement *entryNode in entryNodes) {
					bool isRadio=false;
					ProgramInfo *programInfo=[[[ProgramInfo alloc] init] autorelease];
					CXMLElement *titleNode=[entryNode elementForName:@"title"];
					programInfo.title=titleNode.stringValue;
					NSArray *linkNodes=[entryNode elementsForName:@"link"];
					for(CXMLElement *linkNode in linkNodes) {
						if([[linkNode attributeForName:@"rel"].stringValue isEqualToString:@"alternate"]) {
							programInfo.url=[linkNode attributeForName:@"href"].stringValue;
							CXMLElement *mediaNode=[linkNode elementForName:@"content"];
							if(mediaNode) {
								CXMLElement *thumbnailNode=[mediaNode elementForName:@"thumbnail"];
								if(thumbnailNode) {
									programInfo.thumbnailUrl=[thumbnailNode attributeForName:@"url"].stringValue;
								}
							}
						}
					}
					// work out if this is a tv or radio program
					NSArray *categoryNodes=[entryNode elementsForName:@"category"];
					for(CXMLElement *categoryNode in categoryNodes) {
						if([[categoryNode attributeForName:@"term"].stringValue isEqualToString:@"Radio"]) {
							isRadio=true;
							break;
						}
					}
					
					// get the program updated date
					CXMLElement *updatedNode=[entryNode elementForName:@"updated"];
					NSString *dateString=updatedNode.stringValue;
					programInfo.updated=[dateParser dateFromString:dateString];
					
					// store
					if(isRadio) {
						[radioShows addObject:programInfo];
					} else {
						[tvShows addObject:programInfo];
					}
				}
			}
		}
	}
	// sort the program entries by date
	NSSortDescriptor *sortDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"updated" ascending:false] autorelease];
	[radioShows sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
	[tvShows sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];	
	[self.tableView reloadData];
}

-(IBAction) switchTVRadio {
	[self.tableView reloadData];
}

/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Override to allow orientations other than the default portrait orientation.
    return YES;
}


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return tvRadioSwitch.selectedSegmentIndex == 0 ? tvShows.count : radioShows.count;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	ProgramInfo *programInfo=tvRadioSwitch.selectedSegmentIndex == 0 ? [tvShows objectAtIndex:indexPath.row] : [radioShows objectAtIndex:indexPath.row];
	if(!programInfo.tableCell) {
		programInfo.tableCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:nil] autorelease];
		programInfo.tableCell.textLabel.text=programInfo.title;
		programInfo.tableCell.textLabel.numberOfLines=2;
		programInfo.tableCell.detailTextLabel.text=[programInfo.updated description];
		if(!programInfo.thumbnailDownloaded) {
			programInfo.tableCell.imageView.image=[UIImage imageNamed:@"waiting.jpg"];
			[imageDownloader downloadImage:programInfo];
		}
	}
    return programInfo.tableCell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	ProgramInfo *programInfo=tvRadioSwitch.selectedSegmentIndex==0 ? [tvShows objectAtIndex:indexPath.row] : [radioShows objectAtIndex:indexPath.row];
	[delegate showMovie:programInfo.url];
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
	self.feedUrl = nil;


	self.tableView = nil;

    [super dealloc];
}


@end

